package framework.proxy;

import framework.loadbalance.LoadBalance;
import framework.rpc.client.HttpClient;
import framework.rpc.protocol.http.transport.Invocation;
import framework.rpc.protocol.register.RegisterUrl;
import framework.rpc.protocol.register.RemoteMapRegister;
import provider.api.HellowService;

import javax.websocket.Endpoint;
import java.lang.reflect.Proxy;
import java.util.List;

/**
 * 代理工厂
 *
 * @author ldanniel
 */
public class ProxyFactory<T> {
    public static <T> T getProxy(final Class<HellowService> interfaceClass) {
        try {
            //读取用户配置信息等
            return (T) Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class[]{interfaceClass}, (proxy, method, args) -> {
                HttpClient httpClient = new HttpClient();
                String interfaceName = HellowService.class.getName();
                Invocation invocation = new Invocation(interfaceName, method.getName(), new Class[]{String.class}, args);

                //实现HellowService.class.getName接口指向 localhost 和 8081  -----> 注册中心
                List<RegisterUrl> registryList = RemoteMapRegister.getRegistryList(interfaceName);
                //得到多个请求地址时，就需要实现 负载均衡
                RegisterUrl registerUrl = LoadBalance.loadUrl(registryList);
                return httpClient.send(invocation, registerUrl.getHostName(), registerUrl.getPort());
            });
        } catch (Exception e) {

            //读取配置，重试、重试次数等等容错处理
            return (T) "代理出错了";
        }
    }
}
